/** 登录页 **/
import React, { useState, useEffect } from "react";
import { Form, Input, Button, Checkbox, message } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
// import { useRequest } from "ahooks";
// import CryptoJS from "crypto-js";

import style from "./index.module.less";
import { LoginReqI } from "../../types/api";
import { userLogin } from "../../api/system";
import { store } from "../../store/configureStore";
import { setUserAction } from "../../store/actions";

/**
 * 除了mapState和mapDispatch
 * 每个页面都自动被注入history,location,match 3个对象
 */
// type Props = UserLoginI & {
//   history: History;
//   location: Location;
//   match: match;
// };

// ==================
// 本组件
// ==================
function LoginContainer(): JSX.Element {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false); // 是否正在登录中
  // const [captchaPass, setCaptchaPass] = useState(false); // 验证码是否通过

  // let [captcha, setCaptcha] = useState({
  //   captchaID: "",
  //   imageUrl: "",
  // });

  /**
   * 提交表单且数据在前端验证成功后 执行登录
   */
  const onFinish = (values: LoginReqI) => {
    // captcha 为一次性使用，验证通过后就作废
    // onCaptchaClick();
    console.log(values);
    setLoading(true);
    userLogin(values)
      .then((res) => {
        setLoading(false);
        console.log(res);
        if (res.data.token) {
          store.dispatch(setUserAction(res.data));
          navigate("/");
        } else {
          navigate("/login");
        }
      })
      .catch((err: any) => {
        setLoading(false);
        console.log(err);
        message.error(err.detail);
        navigate("/login");
      });
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log(errorInfo);
    message.error("登录信息填写有误!");
  };

  // 进入登陆页时，判断之前是否保存了用户名和密码
  useEffect(() => {
    // console.log("login");
  }, []);

  return (
    <div className={style.loginPage} data-testid="login">
      <div className={style.header}></div>
      <div className={style.content}>
        <div className={style.title}>
          {/* <h2>空军特色医学中心</h2>
					<h3>{"疲劳预测管理系统"}</h3> */}
          <h3>{"XX系统"}</h3>
        </div>
        <div className={style.loginBox}>
          <Form
            form={form}
            name="login"
            labelCol={{ span: 0 }}
            wrapperCol={{ span: 24 }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            initialValues={{}}
          >
            <div>
              {/* 浏览器会寻找表单中的password输入框，自动填充之前的密码。
                Chrome等浏览器autoComplete=off不起作用。放在这里起到蜜罐
                的作用。但不能解决用户名自动填充和点击真实的密码框下拉列表的问题。
                蜜罐不能用display: "none"或visibility: "hidden"隐藏，否则失效
              */}
              <input
                type="password"
                style={{
                  width: "1px",
                  height: "1px",
                  position: "absolute",
                  border: "0px",
                  padding: "0px",
                }}
              />
              <Form.Item
                name="username"
                rules={[
                  { max: 32, message: "最大长度为32位字符" },
                  {
                    required: true,
                    whitespace: true,
                    message: "请输入用户名",
                  },
                ]}
              >
                <Input
                  prefix={
                    <UserOutlined style={{ fontSize: "@font-size-base" }} />
                  }
                  id="username" // 为了获取焦点
                  type="text"
                  placeholder="用户名"
                  autoComplete="off"
                  data-testid="username"
                />
              </Form.Item>
              <Form.Item
                name="password"
                rules={[
                  { required: true, message: "请输入密码" },
                  { max: 128, message: "最大长度128个字符" },
                ]}
              >
                <Input
                  prefix={
                    <LockOutlined style={{ fontSize: "@font-size-base" }} />
                  }
                  type="password"
                  placeholder="密码"
                  // autoComplete="off"无效，只使用new-password能解决Chrome自动填充问题
                  // 但不解决点击密码框展示存的账号列表，蜜罐用于保险
                  autoComplete="new-password"
                  data-testid="password"
                />
              </Form.Item>
              <Form.Item name="remember" valuePropName="checked">
                <Checkbox>7天内免登录</Checkbox>
              </Form.Item>

              <Form.Item>
                <Button
                  disabled={loading}
                  type="primary"
                  htmlType="submit"
                  style={{ width: "100%" }}
                >
                  登录
                </Button>
              </Form.Item>
              {/* <Form.Item>
              <div className={style.oauth2}>
                <a href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx142df96d5ec3a618&redirect_uri=https://carryon.top/oauth2/weixin&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect">
                  <img src={Weixin} alt="微信授权" />
                  微信授权登录
                </a>
              </div>
            </Form.Item> */}
            </div>
          </Form>
        </div>
      </div>
      <div className={style.footer}></div>
    </div>
  );
}

export default LoginContainer;
